package com.myrealmfrom;

import com.qf.entity.SystemMnue;
import com.qf.entity.UserEmp;
import com.qf.entity.UserRole;
import com.qf.mapper.UserMapper;
import com.qf.service.UserLoginExitService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * 2019/11/26
 * 郭程鹏
 * gcp1909
 * 面向代码面向君,不负时光不负卿
 */

public class ShiroReaml extends  AuthorizingRealm{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserLoginExitService service;
    //认证

    @ResponseBody
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        System.out.println("认证开始");
        //得到用户名
        String username = (String) token.getPrincipal();
        //根据用户名得到密码
        UserEmp userEmp = userMapper.login(username);
        //将得到的密码与用户输入的密码做比较
        if (userEmp==null){
            System.out.println("认证结束");
            return null;
        }else {
            //加盐认证
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(userEmp, userEmp.getPassword(), ByteSource.Util.bytes(userEmp.getSalt()), "gcp");
            System.out.println("结束认证");
            return info;
        }

    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("开始授权");
        //1、得到认证通过后的信息
       UserEmp userEmp= (UserEmp) principals.getPrimaryPrincipal();
        //2、权限=角色+URL
        UserRole role = service.getMenu(userEmp.getRoleId());

        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();

        //角色权限
        simpleAuthorizationInfo.addRole(role.getRoleName());
        System.out.println("当前角色编码"+userEmp.getRoleId());

        //请求权限 得到所有的授权URL
        List<SystemMnue> pressions = userMapper.pressionRole(userEmp.getRoleId());



        ArrayList<String> preCode = new ArrayList<>();

        for (SystemMnue pression : pressions) {
            System.out.println(pression.getPreCode());
            preCode.add(pression.getPreCode());
        }

        //将所有的授权码存入shiro
        simpleAuthorizationInfo.addStringPermissions(preCode);

        return simpleAuthorizationInfo;
    }

}
